package com.zc.portal.infra.security.handler;

import com.alibaba.fastjson.JSON;
import com.zc.commons.pojo.ResponseData;
import com.zc.portal.domain.dto.SysUser;
import com.zc.portal.infra.security.jwt.SecurityJwtUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;
import java.util.stream.Collectors;

public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
        this.onAuthenticationSuccess(request, response, authentication);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException, ServletException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        SysUser sysUser = (SysUser) auth.getPrincipal();
        String token = SecurityJwtUtils.createjwtToken(sysUser, false);
        ResponseData responseData = new ResponseData();
        responseData.setCode(HttpStatus.OK.value());
        responseData.setMessage("Login Success!");
        responseData.setData(token);
        String jsonString = JSON.toJSONString(responseData);
        PrintWriter printWriter = resp.getWriter();
        printWriter.write(jsonString);
        if (printWriter != null) {
            printWriter.flush();
            printWriter.close();
        }
    }
}
